"use client";

//#region import
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { getUserAccount } from "../../../../utils/defender";
import {
  Col,
  Divider,
  Form,
  message,
  Row,
  Select,
  Radio,
  RadioChangeEvent,
  DatePicker,
  Modal,
  Button,
  Tooltip,
} from "antd";
import {
  assesstype,
  radiotype,
  assessresult,
  tablesettingArrInterview,
} from "../../../../utils/static-select";
import {
  GetUinfo,
  GetInterviewInfo,
  SendInterview,
  GetInterviewLines,
} from "@/app/api/operation/interview";
import { TableDataType } from "../../../../utils/publicFuc";
import type {
  InterviewUInfo,
  InterviewData,
  InterviewProject,
  InterviewLines,
} from "../../../../utils/publictype";
import dayjs from "dayjs";
import DetailForm from "@/components/DetailForm";
import { IoAddCircle } from "react-icons/io5";
import { MdAddCircleOutline, MdDelete, MdEdit } from "react-icons/md";
import { FiMinusCircle } from "react-icons/fi";
import TextArea from "antd/es/input/TextArea";
import {
  SaveOutlined,
  SendOutlined,
  SignatureOutlined,
} from "@ant-design/icons";
import { UserModalOp } from "@/components/UserModal";
import SignCom from "@/components/Sign";
import { MdOutlineWarningAmber } from "react-icons/md";
import { UpdateAccFlag } from "@/app/api/operation/improve";
import { FaCircleArrowLeft } from "react-icons/fa6";
//#endregion

export default function Interview() {
  //#region state
  const router = useRouter();
  const params = useSearchParams();
  const [form] = Form.useForm();
  const [UInfo, setUInfo] = useState<InterviewUInfo>();//狀態數據
  const [interviewData, setInterviewData] = useState<InterviewData>({
    docid: params.get("docid") as string,
    assessment_type: "月度考核",
    assessment_result: "",
    assessment_date: dayjs().format("YYYYMM"),
    interview_date: "",
    assessment_next: "",
    last_update_by: "",
  });//表頭數據
  const [editable, setEditalbe] = useState(false);//編輯狀態
  const [signeditable, setSignEditalbe] = useState(false);//簽名按鈕狀態
  const [radiovalue, setRadioValue] = useState();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [signModalOpen, setSignModalOpen] = useState(false);
  const [operation, setOperation] = useState("");//操作方式
  const [intervielines, setInterviewLines] = useState<InterviewLines[]>([
    {
      key: 1,
      value: [],
    },
    {
      key: 2,
      value: [],
    },
  ]);//考核明細數據,默認為兩條
  const [showlines, setShowLines] = useState<InterviewProject[]>([]);//表格顯示數據
  const initialRow: InterviewProject = {
    project: "",
    target: "",
    examine_describe: "",
    improve_describe: "",
    rowid: "",
  };//添加一條數據初始記錄
  const [modifyRow, setModifyRow] = useState<InterviewProject>();//修改數據記錄
  const [assesstypeCur, setAssesstypeCur] = useState(0);//當前選擇類型
  const [collapse, setCollapse] = useState(true);//紅色+號按鈕,打開表單明細控制
  const [sytanxFlag, setSytanxFlag] = useState(false);//異常Flag
  const [changeFlag, setChangeFlag] = useState(0);//用於父組件state變化導致在組件沒有及時渲染而處理的Flag
  const [othercommentsFlag,setOtherCommentsFlag] = useState(false)
  //#endregion

  //#region 初始化
  useEffect(() => {
    if (!getUserAccount()) {
      router.push("/");
      return;
    }
    if (params.get("docid") === "") {
      router.back();
    }
    //獲取狀態
    GetUinfo(
      params.get("docid") as string,
      getUserAccount() as string,
      params.get("type") as string
    ).then(async (res: any) => {
      if (typeof res === "string") {
        message.info("未查找到信息，請確保單號輸入正確！");
        return false;
      }
      const flow_code = res[0][0].flow_code;
      const accept_flag = res[0][0].user_accept_flag;//員工接收Flag
      const manager_save_flag = res[0][0].manager_save_flag;//保存Flag
      if (
        flow_code === "interview_sign_A" ||
        flow_code === "interview_sign_B" ||
        flow_code === "manager_approve_1" ||
        flow_code === "manager_approve_2" ||
        flow_code === "manager_approve_3" ||
        flow_code === "end" ||
        manager_save_flag === "Y"//數據渲染方式為不可編輯、僅可查看
      ) {
        //表頭數據
        GetInterviewInfo(params.get("docid") as string)
          .then(async (res: any) => {
            //表單填值
            form.setFieldValue(
              "assessment_result",
              res[0][0].assessment_result
            );
            if(res[0][0].assessment_result === "其他"){
              form.setFieldValue(
                "assessment_other_comments",
                res[0][0].other_comments
              );
              setOtherCommentsFlag(true)
            }
            form.setFieldValue("assessment_next", res[0][0].assessment_next);
            form.setFieldValue(
              "interview_date",
              dayjs(res[0][0].interview_date, "YYYY-MM-DD")
            );

            if (flow_code !== "interview") setEditalbe(true);
            if (flow_code === "interview_sign_B" && accept_flag === "N") {
              await UpdateAccFlag(params.get("docid") as string, 0, flow_code);//員工查看此信息動作
            }

            setInterviewData(res[0][0]);
            //獲取明細
            const resLine: any = await GetInterviewLines(
              params.get("docid") as string,
              0
            );
            if (resLine !== "success") {
              const temp: InterviewLines[] = [
                {
                  key: 1,
                  value: [],
                },
                {
                  key: 2,
                  value: [],
                },
              ];
              resLine[0].forEach((element: any) => {
                const index = temp.findIndex(
                  (item) => item.key === element.seq
                );
                temp[index].value.push(element);
              });
              setInterviewLines(temp);
              setShowLines(temp[1].value)//默認第二條展開
            }
            if (accept_flag === "Y" && flow_code === "interview_sign_B") {
              UserModalOp.open({
                height: 250,
                conFirmText: "我已了解",
                cancelText: "返回主頁",
                title: "系統提示",
                content: [
                  `如對考核結果有異議，請在三日內提出，否則視為確認，謝謝！`,
                ],
                icon: MdOutlineWarningAmber,
                onConfirm: () => {
                  UserModalOp.close();
                },
                onCancel: () => {
                  UserModalOp.close();
                  router.push("/dashboard");
                },
              });
            }
          })
          .catch(() => {
            message.error("獲取信息錯誤");
            setSytanxFlag(true);
          });
      } else if (flow_code === "interview" && manager_save_flag === "N") { //未保存渲染方式
        const resline: any = await GetInterviewLines(
          params.get("docid") as string,
          2
        );
        if (resline !== "success") {
          const tempdata = intervielines;
          tempdata[1].value = resline[0];
          setInterviewLines(tempdata);
          setShowLines(tempdata[1].value)//默認第二條展開
        }

        UserModalOp.open({
          height: 230,
          conFirmText: "我已了解",
          cancelText: "返回主頁",
          title: "系統提示",
          content: [
            "尊敬的考核主管：請於近期安排與員工的績效面談，重點圍繞以下內容：",
            "1.考核未達標事項;",
            "2.下一考核週期的工作目標;",
            "如有問題請聯系-韋玉芳3776",
          ],
          icon: MdOutlineWarningAmber,
          onConfirm: () => {
            UserModalOp.close();
          },
          onCancel: () => {
            UserModalOp.close();
            router.push("/dashboard");
          },
        });
      }
      setUInfo(TableDataType(res[0][0]));
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  //#endregion

  //#region 送出
  const Submit = async (ope: string) => {
    if(form.getFieldValue("assessment_result") === 3){
      if(form.getFieldValue("assessment_other_comments") === ""){
        message.info("面談結果選擇為--其他。需要填寫備註！")
        return false
      }
    }
    if (
      interviewData.interview_date === "" ||
      interviewData.assessment_next === "" ||
      interviewData.assessment_result === ""
    ) {
      message.info("請確保數據已經填寫完成");
      return false;
    }
    let flag = false;
    const lines: InterviewProject[] = [];
    intervielines.forEach((element) => {
      element.value.forEach((item) => {
        lines.push(item);
        if (
          item.project === "" ||
          item.improve_describe === "" ||
          item.target === "" ||
          item.examine_describe === ""
        ) {
          flag = true;
        }
      });
    });

    if (flag) {
      message.info("請確保表格數據填寫完整！");
      return false;
    }

    const param = {
      ...interviewData,
      last_update_by: getUserAccount(),
      operation: ope,
      comments: "",
      other_comments:form.getFieldValue("assessment_result") === 3 ? form.getFieldValue("assessment_other_comments").toString() :'',
      approve: ope === "send" ? "Y" : "N",
      seq: 0,
      lines: lines,
    };
    try {
      const res: any = await SendInterview(JSON.stringify(param));
      if (res === "success") {
        message.success(ope === "save" ? "保存成功" : "送出成功");
        if (ope === "send") {
          setEditalbe(true);
          router.push("/dashboard");
        }
      }
    } catch {
      message.error("操作失敗");
    }
  };

  //簽名子組件取消
  const signCalcle = () => {
    setSignModalOpen(false);
  };

  //簽名子組件提交
  const signSubmit = () => {
    setEditalbe(true);
    setSignEditalbe(true);
    setSignModalOpen(false);
    router.push("/dashboard");
  };
  //#endregion

  //#region 操作

  //表單操作
  const OperationFunc = (param: InterviewProject | any) => {
    const temp = showlines;
    if (operation === "add") {
      param.seq = assesstypeCur;
      param.rowid = new Date().getTime().toString();
      temp.push(param);
    } else {
      //修改
      temp.forEach((element) => {
        if (element.rowid === param.rowid) {
          element.project = param.project;
          element.target = param.target;
          element.examine_describe = param.examine_describe;
          element.improve_describe = param.improve_describe;
        }
      });
    }
    //同時更改展示數據
    setShowLines(temp);
    const tempall = intervielines;
    const index1 = tempall.findIndex((item) => item.key === assesstypeCur);
    const index = tempall
      .filter((item) => item.key === assesstypeCur)[0]
      .value.findIndex((item1) => item1.rowid === param.rowid);
    tempall[index1].value[index] = param;
    setIsModalOpen(false);
    setInterviewLines(tempall);
    setChangeFlag(changeFlag + 1);
  };

  const closeForm = () => {
    setIsModalOpen(false);
  };

  const Sign = () => {
    setSignModalOpen(true);
  };

  const assessResultChange = (e: number) => {
    if (e === 2) {
      UserModalOp.open({
        height: 320,
        conFirmText: "我已了解",
        cancelText: "關閉",
        title: "系統提示",
        content: [
          "考核主管您好，員工不勝任工作，需進行輔導改善，步驟如下，請知悉！",
          "第1步：主管與員工面談，制定改善計劃；",
          "第2步：員工於期限內完成改善；",
          "第3步：期限結束，主管檢核改善成果，判定是否合格；",
          "第4步：若改善不達標，主管可提報不勝任或給予繼續改善機會。",
          "注：改善總時長須≤3個月",
        ],
        icon: MdOutlineWarningAmber,
        onConfirm: () => {
          UserModalOp.close();
        },
        onCancel: () => {
          UserModalOp.close();
        },
      });
      setOtherCommentsFlag(false)
    }else if(e === 3){
       setOtherCommentsFlag(true)
    }else{
       setOtherCommentsFlag(false)
    }
    setInterviewData({
      ...interviewData,
      assessment_result: assessresult.filter((item) => item.value === e)[0]
        .label,
    });
  };

  const InterlinesOpe = (type: string, rowid: string) => {
    if (type === "modify") {
      setModifyRow(showlines.filter((item) => item.rowid === rowid)[0]);
      setOperation("modify");
      setChangeFlag(changeFlag + 1);
      setIsModalOpen(true);
    } else {
      setShowLines(showlines.filter((item) => item.rowid !== rowid));
      const temp = intervielines;
      const index = temp.findIndex((item) => item.key === assesstypeCur);
      temp[index].value = showlines.filter((item) => item.rowid !== rowid);
      setInterviewLines(temp);
    }
  };

  //#endregion

  //#region JSX生成
  const OperationButton = () => {
    return (
      <Button
        style={{ marginLeft: "30px" }}
        icon={<IoAddCircle style={{ fontSize: "16px" }}></IoAddCircle>}
        disabled={editable}
        onClick={() => {
          setIsModalOpen(true);
          setOperation("add");
        }}
        type="primary"
      >
        添加
      </Button>
    );
  };

  const getAssessShow = () => {
    if (showlines.length > 0) {
      return (
        <>
          <Row
            className="form-row"
            style={{ marginTop: "10px", width: "100%" }}
          >
            <Button
              size="small"
              className="spin-button"
              type="primary"
              danger
              shape="circle"
              icon={
                !collapse ? (
                  <MdAddCircleOutline></MdAddCircleOutline>
                ) : (
                  <FiMinusCircle></FiMinusCircle>
                )
              }
              onClick={() => {
                setCollapse(!collapse);
              }}
            ></Button>
            {getAssessShowDetail()}
          </Row>
        </>
      );
    }
  };

  const getAssessShowDetail = () => {
    if (collapse) {
      return (
        <>
          <ul className="interview-ul">
            <Row className="interview-ul-li">
              <Col span={5}>
                <Tooltip title="主要項目">
                  <span className="interview-ul-span-title interview-ul-span">
                  主要項目
                  </span>
                </Tooltip>
              </Col>
              <Col span={5}>
                <Tooltip title="期望目標">
                  <span className="interview-ul-span-title interview-ul-span">
                    期望目標
                  </span>
                </Tooltip>
              </Col>
              <Col span={5}>
                <Tooltip title="考核說明">
                  <span className="interview-ul-span-title interview-ul-span">
                  考核說明
                  </span>
                </Tooltip>
              </Col>
              <Col span={5}>
                <Tooltip title="不足/需改善之處說明">
                  <span className="interview-ul-span-title interview-ul-span">
                    不足/需改善之處說明
                  </span>
                </Tooltip>
              </Col>
              <Col span={4}>
                <span className="interview-ul-span-title interview-ul-span-last">
                  操作
                </span>
              </Col>
            </Row>
            {showlines.map((item, index) => (
              <Row
                key={index}
                className={
                  showlines.length -
                    1 ===
                  index
                    ? "interview-ul-li-last"
                    : "interview-ul-li"
                }
              >
                <Col span={5}>
                  <Tooltip title={item.project}>
                    <span className="interview-ul-span">{item.project}</span>
                  </Tooltip>
                </Col>
                <Col span={5}>
                  <Tooltip title={item.target}>
                    <span className="interview-ul-span">{item.target}</span>
                  </Tooltip>
                </Col>
                <Col span={5}>
                  <Tooltip title={item.examine_describe}>
                    <span className="interview-ul-span">
                      {item.examine_describe}
                    </span>
                  </Tooltip>
                </Col>
                <Col span={5}>
                  <Tooltip title={item.improve_describe}>
                    <span className="interview-ul-span">
                      {item.improve_describe}
                    </span>
                  </Tooltip>
                </Col>
                <Col span={4}>
                  {item.rowid === "操作" ? (
                    <span
                      className={
                        index === 0
                          ? "interview-ul-span-title interview-ul-span-last"
                          : "interview-ul-span-last"
                      }
                    >
                      {item.rowid}
                    </span>
                  ) : (
                    <span
                      className={
                        index === 0
                          ? "interview-ul-span-title interview-ul-span-last"
                          : "interview-ul-span-last"
                      }
                    >
                      <Button
                        type="primary"
                        icon={<MdEdit></MdEdit>}
                        onClick={() => InterlinesOpe("modify", item.rowid)}
                        disabled={editable}
                      ></Button>
                      <Button
                        type="primary"
                        danger
                        icon={<MdDelete></MdDelete>}
                        onClick={() => InterlinesOpe("delete", item.rowid)}
                        disabled={editable}
                        style={{ marginLeft: "5px" }}
                      ></Button>
                    </span>
                  )}
                </Col>
              </Row>
            ))}
          </ul>
        </>
      );
    }
  };

  const getOperationButton = () => {
    if (
      editable &&
      (UInfo?.flow_code === "interview_sign_A" ||
        UInfo?.flow_code === "interview_sign_B")
    ) {
      return (
        <>
          <Button
            type="primary"
            icon={<SignatureOutlined />}
            onClick={() => Sign()}
            disabled={sytanxFlag || signeditable}
            style={{ margin: "0 20px" }}
          >
            簽名
          </Button>
        </>
      );
    } else if (!editable) {
      return (
        <>
          <Button
            type="primary"
            icon={<SaveOutlined />}
            onClick={() => Submit("save")}
            disabled={sytanxFlag}
            style={{ margin: "0 20px" }}
          >
            儲存
          </Button>
          <Button
            type="primary"
            icon={<SendOutlined />}
            danger
            disabled={sytanxFlag}
            onClick={() => Submit("send")}
          >
            送出
          </Button>
        </>
      );
    }
  };

  const returnManger = () => {
    if (
      UInfo?.flow_code === "manager_approve_1" ||
      UInfo?.flow_code === "manager_approve_2" ||
      UInfo?.flow_code === "manager_approve_3"
    ) {
      return (
        <Button
          type="primary"
          danger
          style={{ marginLeft: "100px" }}
          icon={<FaCircleArrowLeft />}
          onClick={() => {
            router.back();
          }}
        >
          返回
        </Button>
      );
    }
  };
  //#endregion

  //#region render
  return (
    <>
      <div className="interview-operator-1">
        <h3 style={{ display: "inline-block" }}>
          面試記錄訪談表--（{UInfo?.flow_phase}）
        </h3>
        {returnManger()}
      </div>
      <Divider
        style={{ marginTop: "15px", marginBottom: "5px", background: "brown" }}
      ></Divider>
      <div className="interview-box">
        <Form
          form={form}
          className="interviewForm"
          name="interviewForm"
          style={{ marginTop: "10px" }}
        >
          <Row className="form-row">
            <h4>人員基本信息：</h4>
          </Row>
          <Row align="middle" style={{ height: "35px" }} className="form-row">
            <Col span={8}>
              <Form.Item
                name="badge"
                colon={false}
                label={<label className="form-label">工號:</label>}
              >
                <span className="form-label-span">{UInfo?.badge}</span>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="chinese_name"
                colon={false}
                label={<label className="form-label">姓名:</label>}
              >
                <span className="form-label-span">{UInfo?.chinese_name}</span>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="position"
                colon={false}
                label={<label className="form-label">職位:</label>}
              >
                <span className="form-label-span">{UInfo?.position}</span>
              </Form.Item>
            </Col>
          </Row>
          {/* <Divider
            variant="dotted"
            style={{ margin: "8px 0", background: "gray" }}
          ></Divider> */}
          <Row className="form-row">
            <Col span={12}>
              <Form.Item
                name="assessment_type"
                colon={false}
                label={<label className="form-label">面談內容:</label>}
              >
                <Radio.Group
                  className="form-label-span"
                  disabled={editable}
                  options={radiotype}
                  value={radiovalue}
                  defaultValue={2}
                  onChange={(e: RadioChangeEvent) => {
                    setRadioValue(e.target.value);
                    setInterviewData({
                      ...interviewData,
                      assessment_type: radiotype.filter(
                        (item) => item.value === e.target.value
                      )[0].label,
                    });
                  }}
                ></Radio.Group>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="manager_result"
                colon={false}
                label={<label className="form-label">考核結果:</label>}
              >
                <span className="form-label-span">{UInfo?.manager_result}</span>
              </Form.Item>
            </Col>
          </Row>
          {/* <Divider
            variant="dotted"
            style={{ margin: "8px 0", background: "gray" }}
          ></Divider> */}
          <Row className="form-row">
            <Col span={12}>
              <Form.Item
                name="assessment_date"
                colon={false}
                label={<label className="form-label">考核時間:</label>}
              >
                <span className="form-label-span">
                  {dayjs().format("YYYYMM")}
                </span>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="interview_date"
                colon={false}
                label={<label className="form-label">面談時間:</label>}
              >
                <DatePicker
                  disabled={editable}
                  style={{ color: editable ? "white" : "black" }}
                  className="form-change-width"
                  onChange={(e) => {
                    setInterviewData({
                      ...interviewData,
                      interview_date: e.format("YYYY-MM-DD"),
                    });
                  }}
                ></DatePicker>
              </Form.Item>
            </Col>
          </Row>
          <Divider style={{ margin: "5px 0", background: "gray" }}></Divider>
          <Row className="form-row">
            <h4 style={{ margin: "5px 0" }}>考核結果說明：</h4>
          </Row>
          <Row className="form-row">
            <Form.Item
              name="type"
              colon={false}
              label={<label className="form-label">考核類型:</label>}
            >
              <Select
                className="form-change-width"
                optionFilterProp="label"
                options={assesstype}
                defaultValue={2}
                style={{ color: editable ? "white" : "black" }}
                onChange={(e) => {
                  setAssesstypeCur(e);
                  setShowLines(
                    intervielines.filter((item) => item.key === e)[0].value
                  );
                }}
              ></Select>
              {OperationButton()}
            </Form.Item>
          </Row>
          {getAssessShow()}
          <Divider style={{ margin: "5px 0", background: "gray" }}></Divider>
          <Row className="form-row">
            <h4 style={{ margin: "5px 0" }}>績效面談結果：</h4>
          </Row>
          <Row className="form-row">
            <Col>
              <Form.Item
                name="assessment_result"
                colon={false}
                label={<label className="form-label">面談結果:</label>}
              >
                <Select
                  className="form-change-width"
                  optionFilterProp="label"
                  options={assessresult}
                  disabled={editable}
                  style={{ color: editable ? "white" : "black" }}
                  onChange={(e) => assessResultChange(e)}
                ></Select>
              </Form.Item>
            </Col>
            {othercommentsFlag ? (
              <Col style={{marginLeft:'20px'}}>
              <Form.Item
                name="assessment_other_comments"
                colon={false}
                label={<label className="form-label">備註:</label>}
              >
                <TextArea
                  disabled={editable}
                  style={{ color: editable ? "white" : "black",width:'300px' }}
                ></TextArea>
              </Form.Item>
            </Col>
            ) : null}
          </Row>
          <Divider style={{ margin: "5px 0", background: "gray" }}></Divider>
          <Row className="form-row">
            <h4 style={{ margin: "5px 0" }}>
              下一考核週期的工作計劃/工作內容、工作目標:
            </h4>
          </Row>
          <Row className="form-row">
            <Col>
              <Form.Item
                name="assessment_next"
                colon={false}
                label={<label className="form-label">此處填寫:</label>}
              >
                <TextArea
                  disabled={editable}
                  style={{ color: editable ? "black" : "black" }}
                  rows={3}
                  className="form-change-width-textarea"
                  onChange={(e) =>
                    setInterviewData({
                      ...interviewData,
                      assessment_next: e.target.value,
                    })
                  }
                ></TextArea>
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <Modal
          closable={false}
          open={isModalOpen}
          className="interview-modal"
          height={600}
          wrapClassName="single-form"
          footer={[]}
        >
          <DetailForm
            singleRow={operation === "add" ? initialRow : modifyRow}
            formsettiing={tablesettingArrInterview}
            operation={operation}
            Submit={OperationFunc}
            Cancle={closeForm}
            updateFlag={changeFlag}
          ></DetailForm>
        </Modal>
      </div>
      <Divider style={{ margin: "5px 0", background: "brown" }}></Divider>
      <div className="interview-operator">{getOperationButton()}</div>
      <Modal
        closable={false}
        open={signModalOpen}
        height={500}
        width={600}
        wrapClassName="single-form"
        footer={[]}
      >
        <SignCom
          docid={interviewData.docid}
          flow_code={UInfo?.flow_code as string}
          flow_phase={UInfo?.flow_phase as string}
          seq={0}
          onCancel={() => signCalcle()}
          onSubmit={() => signSubmit()}
        ></SignCom>
      </Modal>
    </>
  );
  //#endregion
}
